package com.sz.admin.system.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sz.admin.system.service.OcrRecognitionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;

/**
 * OCR识别服务实现类
 *
 * @author sz-admin
 * @since 2025-09-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OcrRecognitionServiceImpl implements OcrRecognitionService {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    //private static final String OCR_API_URL = "http://localhost:8001/api/ocr/recognize";
    // private static final String OCR_API_URL = "http://localhost:8001/api/ocr/digits_without_license_plate";
    private static final String OCR_API_URL = "http://localhost:8001/ocr/";

    @Override
    public OcrResult recognizeText(File imageFile) {
        try {
            // 准备请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 准备文件参数
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", new FileSystemResource(imageFile));

            // 创建请求实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            log.debug("调用OCR服务识别图片: {}", imageFile.getName());

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                OCR_API_URL, 
                HttpMethod.POST, 
                requestEntity, 
                String.class
            );

            // 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                String responseBody = response.getBody();
                log.debug("OCR服务响应: {}", responseBody);

                // 解析响应JSON
                JsonNode jsonNode = objectMapper.readTree(responseBody);
                
                boolean success = jsonNode.path("success").asBoolean(false);
                if (success) {
                    // Extract car_number from the response for carNumber
                    String carNumber = jsonNode.path("data").path("car_number").asText("");
                    // Use the entire recognized_text array as the fullResponse (which becomes carNumberRes)
                    JsonNode recognizedText = jsonNode.path("data").path("recognized_text");
                    String fullResponse = recognizedText.toString();
                    log.info("OCR识别成功，文件: {}, 车牌号: {}", imageFile.getName(), carNumber);
                    return new OcrResult(true, carNumber, fullResponse, null);
                } else {
                    String message = jsonNode.path("message").asText("OCR识别失败");
                    log.warn("OCR识别失败，文件: {}, 错误信息: {}", imageFile.getName(), message);
                    return new OcrResult(false, null, responseBody, message);
                }
            } else {
                String errorMsg = "OCR服务响应异常，状态码: " + response.getStatusCode();
                log.error(errorMsg);
                return new OcrResult(false, null, null, errorMsg);
            }

        } catch (Exception e) {
            String errorMsg = "调用OCR服务异常: " + e.getMessage();
            log.error(errorMsg, e);
            return new OcrResult(false, null, null, errorMsg);
        }
    }
}